<template>
	<div class="w100">
		<el-tree-select
			v-if="detail === false"
			ref="TreeSelect"
			:data="options"
			clearable
			filterable
			check-strictly
			collapse-tags
			collapse-tags-tooltip
			node-key="id"
			@node-click="selectChange"
			v-bind="$attrs"
		>
			<template v-for="(slotKey, slotIndex) in Object.keys($slots)" :key="slotIndex" v-slot:[slotKey]>
				<slot :name="slotKey"></slot>
			</template>
		</el-tree-select>
		<template v-else>
			{{
				selectDictLabel(treeRevert(options, $attrs['node-key'] || $attrs['nodeKey'] || 'id'), $attrs.modelValue, ',', {
					dictValue: $attrs.props.value,
					dictLabel: $attrs.props.label
				})
			}}
		</template>
	</div>
</template>

<script setup name="MyTreeSelect">
import { API_HOST } from '@/config'
import axios from '@u/axios'
import _camelCase from 'lodash/camelCase'
import { treeRevert } from '@u/tree'

const TreeSelect = shallowRef(null),
	/***
	 * 参数属性
	 * @property {list[]} list 数据源
	 * @property {String} type store.dispatch的方法名,兼容'GETdeptTree'/'deptTree'/'dept_tree'三种方式
	 * @property {String，Function} api 数据请求地址，默认请求为·GET·方式，支持传递url地址、api请求方法两种
	 * @property {Boolean} detail 是否为详情展示形式，默认为false
	 */
	props = defineProps({
		type: {
			type: String
		},
		list: {
			type: Array,
			default: () => []
		},
		api: {
			type: [String, Function],
			default: ''
		},
		detail: {
			type: Boolean,
			default: false
		}
	})

const dictType = computed(() => (props.type ? (props.type?.startsWith?.('GET') ? props.type : `GET${_camelCase(props.type)}`) : '')),
	options = ref([])

watch(
	() => props.list,
	(val) => {
		options.value = val || []
	},
	{ deep: true, immediate: true }
)

watch(
	() => props.api,
	(val) => {
		if (val) {
			if (typeof val === 'string') {
				axios({
					method: 'get',
					url: API_HOST + val
				}).then((res) => {
					options.value = res.data || []
				})
			}
			if (typeof val === 'function') {
				val().then((res) => {
					options.value = res.data || []
				})
			}
		}
	},
	{ immediate: true }
)

watch(
	() => $store?.com[unref(dictType)?.replace('GET', '')],
	(val) => {
		if (unref(dictType)) options.value = val
	},
	{ deep: true, immediate: true }
)

/**
 * 初始化执行逻辑
 */
if (unref(dictType)) {
	const dictTypeFn = $store?.com[unref(dictType)]
	if (isFunction(dictTypeFn)) {
		dictTypeFn()
	} else {
		throw new Error('type 全局数据传入，但无对应执行方法！')
	}
}

// 获取label
const attrs = useAttrs(),
	emits = defineEmits(['getLabel'])
function selectChange() {
	if (!attrs.multiple) {
		emits('getLabel', unref(TreeSelect).getCurrentNode()?.[attrs.props.label] || '')
	} else {
		nextTick(() => {
			let labelArr = []
			attrs.modelValue.forEach((id) => {
				let label = unref(TreeSelect).getNode(id).data[attrs.props.label]
				labelArr.push(label)
			})
			emits('getLabel', labelArr)
		})
	}
}
</script>
